﻿Imports System.Net
Imports System.IO

Partial Class webservices_ipn : Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'Read/Parse params
        Dim params As Byte() = Request.BinaryRead(Request.ContentLength)
        Dim strRequest As String = Encoding.ASCII.GetString(params)
        'CAudit_Error.Log(New Exception("IPN: " & strRequest)) 'temp:debug!!

        Dim dict As Dictionary(Of String, String) = CPayment.Split(strRequest)
        If dict.Count = 0 Then Exit Sub

        'Get the details
        Dim orderId As String = String.Empty
        Dim gross As String = String.Empty
        Dim fee As String = String.Empty
        Dim memo As String = String.Empty
        Dim ccy As String = String.Empty
        Dim txnId As String = String.Empty
        Dim itemName As String = String.Empty
        Dim firstName As String = String.Empty
        Dim lastName As String = String.Empty

        dict.TryGetValue("custom", orderId)

        dict.TryGetValue("mc_gross", gross)
        dict.TryGetValue("mc_fee", fee)
        dict.TryGetValue("mc_currency", ccy)
        dict.TryGetValue("txn_id", txnId)

        dict.TryGetValue("memo", memo)
        dict.TryGetValue("item_name", itemName)
        dict.TryGetValue("first_name", firstName)
        dict.TryGetValue("last_name", lastName)

        'Record the purchase
        With New CPayment
            .PaymentOrderId = CTextbox.GetInteger(orderId)
            .PaymentDetails = strRequest

            .PaymentAmount = CTextbox.GetMoney(gross)
            .PaymentFee = CTextbox.GetMoney(fee)
            .PaymentCurrency = ccy
            .paymentTransaction = txnId

            .PaymentIsOk = False
            .PaymentCode = "acknowledging..."

            .PaymentFirstName = firstName
            .PaymentLastName = lastName
            .PaymentItemName = itemName
            .PaymentMemo = memo

            .Save()

            'Reply to Paypal
            Dim code As String = Nothing
            If Not Acknowledge(strRequest, code) Then
                .PaymentCode = code
                .Save()
                Exit Sub
            End If

            'Check the receipt
            .PaymentCode = dict("payment_status")
            .PaymentIsOk = (LCase(.PaymentCode) = "completed")
            .PaymentTransaction = dict("txn_id")
            .Save()

            If Not .PaymentIsOk Then
                .Reload(Nothing)
                CAudit_Error.Log(New Exception("payment_status <> COMPLETED: " & .PaymentCode), .CustomerEmail, .CustomerName)
                Exit Sub
            End If

            Try
                If .PaymentOrderId > 0 AndAlso .PaymentAmount >= .Order.OrderPriceHistorical Then
                    With .Order
                        .OrderIsPaid = True
                        .Save()
                    End With
                End If
            Catch
            End Try
        End With
    End Sub

    Private Function Acknowledge(ByVal strRequest As String, ByRef strResponse As String) As Boolean
        strRequest &= "&cmd=_notify-validate"

        'Post back to either sandbox or live
        Dim req As HttpWebRequest = WebRequest.Create(CConfig.Paypal)
        req.Method = "POST"
        req.ContentType = "application/x-www-form-urlencoded"
        req.ContentLength = strRequest.Length

        'for proxy
        'Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
        'req.Proxy = proxy

        'Send the request to PayPal and get the response
        Dim s_out As New StreamWriter(req.GetRequestStream(), Encoding.ASCII)
        s_out.Write(strRequest)
        s_out.Close()

        Dim s_in As New StreamReader(req.GetResponse().GetResponseStream())
        strResponse = s_in.ReadToEnd()
        s_in.Close()

        If strResponse = "VERIFIED" Then
            'check the payment_status is Completed
            'check that txn_id has not been previously processed
            'check that receiver_email is your Primary PayPal email
            'check that payment_amount/payment_currency are correct
            'process payment
            Return True
        ElseIf strResponse = "INVALID" Then
            'log for manual investigation
            CAudit_Error.Log(New Exception("INVALID response from Paypal"))
            Return False
        Else
            'Response wasn't VERIFIED or INVALID, log for manual investigation
            CAudit_Error.Log(New Exception("Unexpected response from Paypal: " & strResponse))
            Return False
        End If
    End Function

End Class
